<template>
  <div class="cu-common-layout">
    <div class="cu-common-layout-center">
      <el-row class="cu-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="6">
            <el-form-item label="师训标题">
              <el-input v-model="query.title" placeholder="师训标题" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="报名日期">
              <el-date-picker v-model="query.registDate" type="daterange" value-format="yyyy-MM-dd" format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()" native-type="submit">{{ $t('common.search') }}</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset()">{{ $t('common.reset') }}</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="cu-common-layout-main cu-flex-main">
        <div class="cu-common-head">
          <div>
            <el-button type="primary" icon="el-icon-plus" @click="addOrUpdateHandle()" v-has="'btn_add'">新增</el-button>
            <el-button type="primary" icon="el-icon-plus" @click="addHistoryHandle()">补录</el-button>
          </div>
          <div class="cu-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link icon="icon-ym icon-ym-Refresh cu-common-head-icon" :underline="false" @click="reset()" />
            </el-tooltip>
            <screenfull isContainer />
          </div>
        </div>
        <custom-table v-loading="listLoading" :data="list">
          <el-table-column v-if="custom.hasP('picture')" prop="picture" label="宣传图片" align="center">
            <template slot-scope="scope">
              <el-image v-if="scope.row.picture != null" :src="JSON.parse(scope.row.picture)[0].url" fit="scale-down" :preview-src-list="[JSON.parse(scope.row.picture)[0].url]" min-width="100" height="30"></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="picture" label="签到码" align="center" width="80">
            <template slot-scope="scope">
              <el-button type="text" @click="downloadQRCode(scope.row)">下载</el-button>
            </template>
          </el-table-column>

          <el-table-column prop="title" label="师训标题" align="left" v-if="custom.hasP('title')" show-overflow-tooltip width="200" />
          <el-table-column label="品牌" prop="brand" align="center" width="200">
            <template slot-scope="scope">
              {{ JSON.parse(scope.row.brand) | dynamicCodeText(brandOptions) }}
            </template>
          </el-table-column>
          <el-table-column label="师训类型" prop="typeId" align="center" v-if="custom.hasP('typeId')">
            <template slot-scope="scope">
              {{ scope.row.typeId | dynamicCodeText(typeIdOptions) }}
            </template>
          </el-table-column>
          <el-table-column prop="enCode" label="证书编号" align="left" v-if="custom.hasP('enCode')" width="130" />
          <el-table-column label="证书模版" prop="certificateTemplate" align="left" width="120" v-if="custom.hasP('certificateTemplate')">
            <template slot-scope="scope">
              {{ scope.row.certificateTemplate | dynamicTreeCodeText(certificateTemplateOptions) }}
            </template>
          </el-table-column>
          <el-table-column prop="free" label="是否免费" align="center" v-if="custom.hasP('free')">
            <template slot-scope="scope">
              <el-tag :key="scope.row.free" v-if="!scope.row.free" type="" effect="dark">收费</el-tag>
              <el-tag :key="scope.row.free + 1" v-else type="success" effect="dark">免费</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="收费价格" align="center" v-if="custom.hasP('price')" width="100px">
            <template slot-scope="scope">
              <el-tag type="success">{{ scope.row.price | currency('¥') }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="overPriceEnabled" label="允许超额" align="center" width="80px">
            <template slot-scope="scope">
              <el-tag :type="scope.row.overPriceEnabled ? 'success' : 'info'">{{ scope.row.overPriceEnabled ? '是' : '否' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="overPrice" label="超额价格" align="center" width="100px">
            <template slot-scope="scope">
              <el-tag type="warning">{{ (scope.row.overPrice || 0) | currency('¥') }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="maxPerson" label="参训总人数" align="center" v-if="custom.hasP('maxPerson')" width="60px" />
          <el-table-column prop="campsMaxPerson" label="校区参训名额" align="center" v-if="custom.hasP('campsMaxPerson')" />
          <el-table-column prop="signNum" label="已报名人数" align="center" width="60px">
            <template slot-scope="scope">
              <el-button type="text" @click="goTrainorder(scope.row)">{{ scope.row.signNum }}</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="registerStartDate" label="报名时间" align="center" v-if="custom.hasP('registerStartDate')" width="160px">
            <template slot-scope="scope">
              <span>{{ custom.tableDateFormat(scope.row, 'registerStartDate', scope.row.registerStartDate) + ' ~ ' + custom.tableDateFormat(scope.row, 'registerEndDate', scope.row.registerEndDate) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="startDate" label="师训时间" align="center" v-if="custom.hasP('startDate')" width="200px">
            <template slot-scope="scope">
              <span>{{ custom.tableDateTimeFormat(scope.row, 'startDate', scope.row.startDate) + ' ~ ' + custom.tableDateTimeFormat(scope.row, 'endDate', scope.row.endDate) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="nper" label="期数" align="left" v-if="custom.hasP('nper')" width="60px" />
          <el-table-column prop="sortCode" label="排序" align="left" width="60px" />
          <el-table-column prop="enabledMark" label="是否下架" align="left" v-if="custom.hasP('enabledMark')">
            <template slot-scope="scope">
              <el-switch style="display: block" v-model="scope.row.enabledMark" @change="handleEnabledMarkChange(scope.row)" :active-value="1" :inactive-value="0"></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="createUserName" label="创建用户" align="left" v-if="custom.hasP('createUserName')" />
          <el-table-column prop="createTime" label="创建时间" :formatter="custom.tableDateTimeFormat" align="center" v-if="custom.hasP('createTime')" width="120px" />
          <el-table-column prop="updateUserName" label="修改用户" align="left" v-if="custom.hasP('updateUserName')" />
          <el-table-column prop="updateTime" label="修改时间" align="center" :formatter="custom.tableDateTimeFormat" v-if="custom.hasP('updateTime')" width="120px" />
          <el-table-column label="操作" fixed="right" width="160px" align="center">
            <template slot-scope="scope">
              <table-opts @edit="addOrUpdateHandle(scope.row.id)" @del="handleDel(scope.row.id)">
                <el-button type="text" v-has="'btn_sign'" @click="signHandle(scope.row)">报名</el-button>
                <el-button type="text" v-has="'btn_deduction'" @click="addDeductionHandle(scope.row.id)">抵扣</el-button>
                <el-button type="text" v-has="'btn_signtime_config'" @click="signTimeConfigHandle(scope.row.id)">签到配置</el-button>
              </table-opts>
            </template>
          </el-table-column>
        </custom-table>

        <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="initData" />
      </div>
    </div>
    <custom-form v-if="formVisible" ref="CustomForm" @refresh="search" />
    <order-form v-if="orderFormVisible" ref="OrderForm" @refresh="search" />
    <history-form v-if="historyFormVisible" ref="HistoryForm" @refresh="search" />
    <deduction-form v-if="deductionFormVisible" ref="DeductionForm" @refresh="search" />
    <sign-time-config v-if="signTimeConfigVisible" ref="SignTimeConfig" @refresh="search" />
  </div>
</template>
<script>
import CustomForm from './Form'
import HistoryForm from './HistoryForm/index.vue'
import DeductionForm from './DeductionForm/index.vue'
import SignTimeConfig from './SignTimeConfig/index.vue'
import OrderForm from '../trainorder/Form'
import QRCode from 'qrcode'
import { getTrainList, delTrain, changeEnabledMark } from '@/api/campus/train'
export default {
  name: 'train_release',
  components: { CustomForm, OrderForm, HistoryForm, DeductionForm, SignTimeConfig },
  data() {
    return {
      query: {
        title: undefined,
        registDate: undefined,
        typeId: undefined
      },
      treeProps: {
        children: 'children',
        label: 'fullName',
        value: 'id'
      },
      list: [],
      listLoading: true,
      historyFormVisible: false,
      deductionFormVisible: false,
      multipleSelection: [],
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'sortCode desc,createTime'
      },
      formVisible: false,
      orderFormVisible: false,
      exportBoxVisible: false,
      signTimeConfigVisible: false,
      columnList: [{ prop: 'picture', label: '宣传图片' }, { prop: 'enCode', label: '师训编号', width: 120 }, { prop: 'title', label: '师训标题', width: 200 }, { prop: 'typeId', label: '师训类型', width: 120 }, { prop: 'certificateTemplate', label: '证书模版', width: 120 }, { prop: 'free', label: '是否免费', align: 'center' }, { prop: 'price', label: '收费价格' }, { prop: 'overPriceEnabled', label: '允许超额', align: 'center' }, { prop: 'overPrice', label: '超额价格', align: 'center' }, { prop: 'maxPerson', label: '师训总人数', align: 'center' }, { prop: 'campsMaxPerson', label: '校区参训名额', width: 100, align: 'center' }, { prop: 'registerStartDate', label: '报名开始日期', formatter: this.custom.tableDateFormat, width: 120, align: 'center' }, { prop: 'registerEndDate', label: '报名结束日期', formatter: this.custom.tableDateFormat, width: 100, align: 'center' }, { prop: 'startDate', label: '师训开始日期', formatter: this.custom.tableDateFormat, width: 100, align: 'center' }, { prop: 'endDate', label: '师训结束日期', formatter: this.custom.tableDateFormat, width: 100, align: 'center' }, { prop: 'nper', label: '师训期数', align: 'center' }, { prop: 'address', label: '师训地址' }, { prop: 'enabledMark', label: '是否下架', align: 'center' }, { prop: 'sortCode', label: '发布排序', align: 'center' }, { prop: 'createTime', label: '创建时间', formatter: this.custom.tableDateTimeFormat, width: 140, align: 'center' }, { prop: 'createUserName', label: '创建用户' }, { prop: 'updateTime', label: '修改时间', formatter: this.custom.tableDateTimeFormat, width: 140, align: 'center' }, { prop: 'updateUserName', label: '修改用户' }],
      typeIdOptions: [],
      certificateTemplateOptions: [],
      brandOptions: []
    }
  },
  computed: {},
  created() {
    this.initData()
    this.getTypeIdOptions()
    this.getCertificateTemplateOptions()
    this.$store.dispatch('base/getDictionaryData', { sort: 'Brand' }).then(res => {
      this.brandOptions = res
    })
  },
  methods: {
    async downloadQRCode(item) {
      try {
        // 替换成你的目标URL
        if (!item.latitude || !item.longitude) {
          this.$message({
            message: '请设置师训坐标',
            type: 'error',
            duration: 1000
          })
          return
        }
        const targetUrl = `https://trainsign.anqinyun.com/verify?id=${item.id}`

        // 生成Data URL（默认尺寸为 200x200）
        const dataUrl = await QRCode.toDataURL(targetUrl, {
          width: 200,
          margin: 2
        })

        // 创建隐藏的下载链接
        const link = document.createElement('a')
        link.href = dataUrl
        link.download = `qrcode-${Date.now()}.png` // 使用时间戳保证文件名唯一

        // 触发下载
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      } catch (error) {
        console.error('二维码生成失败:', error)
        alert('二维码生成失败，请稍后重试')
      }
    },
    getTypeIdOptions() {
      this.$store.dispatch('base/getDictionaryData', { sort: 'TrainType' }).then(res => {
        this.typeIdOptions = res
      })
    },
    getCertificateTemplateOptions() {
      this.$store.dispatch('base/getDictionaryData', { sort: 'TrainCertificateType' }).then(res => {
        console.log(res)
        this.certificateTemplateOptions = res
      })
    },
    initData() {
      this.listLoading = true
      let _query = {
        ...this.listQuery,
        ...this.query
      }
      let query = {}
      for (let key in _query) {
        if (Array.isArray(_query[key])) {
          query[key] = _query[key].join()
        } else {
          query[key] = _query[key]
        }
      }
      getTrainList(query).then(res => {
        this.list = res.data.list
        this.total = res.data.pagination.total
        this.listLoading = false
      })
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(() => {
          delTrain(id).then(res => {
            this.$message({
              type: 'success',
              message: res.msg,
              onClose: () => {
                this.initData()
              }
            })
          })
        })
        .catch(() => {})
    },
    addOrUpdateHandle(id, isDetail) {
      this.formVisible = true
      this.$nextTick(() => {
        this.$refs.CustomForm.init(id, isDetail)
      })
    },
    addHistoryHandle(id, isDetail) {
      this.historyFormVisible = true
      this.$nextTick(() => {
        this.$refs.HistoryForm.init(id, isDetail)
      })
    },
    addDeductionHandle(id) {
      this.deductionFormVisible = true
      this.$nextTick(() => {
        this.$refs.DeductionForm.init(id)
      })
    },
    signHandle(row) {
      this.orderFormVisible = true
      this.$nextTick(() => {
        this.$refs.OrderForm.sign(row)
      })
    },
    goTrainorder(row) {
      this.$router.push({
        path: '/campus/trainorder',
        query: {
          title: row.title
        }
      })
    },
    handleNodeClick(data) {
      this.treeActiveId = data.id
      for (let key in this.query) {
        this.query[key] = undefined
      }
      this.query.typeId = data.id
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'sortCode desc,createTime'
      }
      this.initData()
    },

    search() {
      this.formVisible = false
      this.orderFormVisible = false
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'sortCode desc,createTime'
      }
      this.initData()
    },
    refresh(isrRefresh) {
      this.formVisible = false
      if (isrRefresh) this.reset()
    },
    reset() {
      for (let key in this.query) {
        this.query[key] = undefined
      }
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'sortCode desc,createTime'
      }
      this.initData()
    },
    handleEnabledMarkChange(row) {
      let text = row.enabledMark == 0 ? '上架' : '下架'
      this.$confirm('确认要操作' + text + '师训吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.listLoading = true
          changeEnabledMark({ id: row.id, enabledMark: row.enabledMark }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 1000,
              onClose: () => {
                this.listLoading = false
                this.search()
              }
            })
          })
        })
        .catch(() => {
          //取消
          row.enabledMark = row.enabledMark === 1 ? 0 : 1
        })
    },
    signTimeConfigHandle(trainId) {
      // 打开签到时间配置页面
      this.signTimeConfigVisible = true
      this.$nextTick(() => {
        this.$refs.SignTimeConfig.init(trainId)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.el-table__fixed-right {
  height: 100% !important;
}
</style>
